package com.util.aliyun;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * Created by reeveslee on 16/5/16.
 */
public class OCSutils {
    // 阿里云测试缓存数据库
    private static final String HOST = "c59d7de7dec04f20.m.cnqdalicm9pub001.ocs.aliyuncs.com";
    // 阿里云正式缓存服务器
    // private static final String HOST = "ae46191f31834680.m.cnhzaliqshpub001.ocs.aliyuncs.com";
    private static final String PORT = "11211";
    private static final Logger LOGGER = Logger.getLogger(OCSutils.class);

    private static MemcachedClient cache;

    public OCSutils() {
        this.cache = null;
        try {
            this.cache = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(HOST + ":" + PORT));
        } catch (IOException e) {
            LOGGER.error("初始化OCS客户端错误");
        }
    }

    /**
     * 存储键值对数据
     *
     * @param key
     * @param value
     * @return
     */
    public boolean save(String key, Object value, int expire) {
        cache.set(key, expire, value);
        return true;
    }

    /**
     * 获取键值对数据
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return cache.get(key);
    }

    /**
     * 删除
     *
     * @param key
     * @return
     */
    public boolean delete(String key) {
        return cache.delete(key).isDone();
    }
}
